package com.msb.iterator.v5;

import java.util.Arrays;

public class _ArrayList implements _Collection {

    Object[] objects = new Object[10];
    private int index = 0;

    @Override
    public void add(Object o) {
        if (index == objects.length) {
            Object[] newObjects = new Object[objects.length * 2];
            System.arraycopy(objects, 0, newObjects, 0, objects.length);
            objects = newObjects;
        }

        objects[index++] = o;
    }

    @Override
    public int size() {
        return index;
    }

    @Override
    public _Iterator iterator() {
        return new ArrayListIterator();
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("_ArrayList{");
        sb.append("objects=").append(objects == null ? "null" : Arrays.asList(objects).toString());
        sb.append(", index=").append(index);
        sb.append('}');
        return sb.toString();
    }

    private class ArrayListIterator implements _Iterator {

        private int currentIndex = 0;

        @Override
        public boolean hasNext() {
            if (currentIndex >= index) {
                return false;
            }
            return true;
        }

        @Override
        public Object next() {
            Object o = objects[currentIndex];
            currentIndex++;
            return o;
        }
    }
}
